#include <lib/stdio.h>
#include <lib/stdlib.h>
#include <os/debug.h>

#define NUM_DIGHT_ASCII 48
#define NUM_CHAR_ASCII 97

char *itoa(int num, int base, char *str, int prefix)
{
    int n = num;
    int count = 0; // bits count
    char ch[32];   // bits char
    char *s = str;
    int len;

    memset(ch, 0, 32);

    switch (base)
    {
    case 10: // 十进制
    {
        base = 10;
        while (n)
        {
            ch[count] = n % base + NUM_DIGHT_ASCII;
            count++;
            n = n / base;
        }
    }
    break;
    case 8: // 八进制
    {
        base = 8;
        while (n)
        {
            ch[count] = n % base + NUM_DIGHT_ASCII;
            count++;
            n = n / base;
        }
    }
    break;
    case 16: // 十六进制
    {
        base = 16;
        while (n)
        {
            ch[count] = (n % base) < 0xA ? (n / base) + NUM_DIGHT_ASCII : ((n / base) - 0xA) + NUM_CHAR_ASCII;
            count++;
            n = n / base;
        }
    }
    break;
    default:
        break;
    }
    // get strlen
    len = strlen(ch);

    if (prefix) // add prefix
    {
        if (base == 10 && num < 0)
            *s++ = '-';
        else
        {
            if (base == 16)
            {
                *s++ = '0';
                *s++ = 'x';
            }
            else if (base == 8)
            {
                *s++ = '0';
            }
        }
    }

    for (int i = len; i > 0; i--)
    {
        *s++ = ch[i - 1];
    }
    *s = '\0';
    return str;
}